const db = wx.cloud.database()
var myDate = new Date()
var myTime=myDate.toLocaleString()
Page({
  data: {
    upload_button_message: "拍照识别",
    disable_upload_button: false,
    src: "",
    base64:"",
    baidutoken:"",
    visitor_id:"",
    name:"",
  },

  takePhoto() {
    let that = this;
    that.setData({
      upload_button_message: "正在处理...",
      disable_upload_button: true
    })
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'normal',
      success: (res) => {
        this.setData({
          src: res.tempImagePath //获取图片
        })
        //图片base64编码
        wx.getFileSystemManager().readFile({
          filePath: this.data.src, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            this.setData({
              base64: res.data
            })
          },
          fail(res){
              console.log("Fail to take photo:  ",res)
            wx.showToast({
                title: '请重试',
                icon: 'loading',
                duration: 500
              })
          }
        })
        this.getBaiduToken();
      } //拍照成功结束
    }) //调用相机结束

  },
  error(e) {
    console.log(e.detail)
  },
  getBaiduToken() {
    var that = this;
    //acess_token获取,qs:需要多次尝试
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token', //是真实的接口地址
      data: {
        grant_type: 'client_credentials',
        client_id: '', //用你创建的应用的API Key
        client_secret: '' //用你创建的应用的Secret Key
      },
      header: {
        'Content-Type': 'application/json' // 默认值
      },
      success(res) {
          console.log("Success to get token:",res)
        that.setData({
          baidutoken: res.data.access_token //获取到token
        })
        that.recognize();
      },
      fail(res) {
          console.log("Fail to get token: ",res)
      }
    })
  },
  recognize(){
    var that = this;
    console.log("token: ",that.data.baidutoken)
console.log("Begin to recognize.")

    wx.request({
        url: 'https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=' + that.data.baidutoken,
        method: 'POST',
        data: {
          image: this.data.base64,
          image_type: 'BASE64',
          group_id_list: 'visitor', //自己建的用户组id
        },
        header: {
          'Content-Type': 'application/json' // 默认值
        },
        success(res) {
         console.log("Success to recognize:",res)
        that.setData({
            upload_button_message: "重新识别",
            disable_upload_button: false,
        })
          //做成功判断
          if (res.data.error_msg == "pic not has face") {
            wx.showToast({
              title: '未捕获到人脸',
              icon: 'error',
            })
          }
          if (res.data.error_msg == 'SUCCESS') {
            if(res.data.result.user_list[0].score>80){
                that.setData({
                    visitor_id:res.data.result.user_list[0].user_id
                })
                
         
            that.uploadMessage();
            }else{
              wx.showToast({
                title: '人脸识别失败',
                icon: 'error',
              })
            }
          }
        },
        fail(res){
            console.log("Fail to recognize:",res)
        }
      });
 
  },
  uploadMessage(){
      
      var that=this
      try {
          db.collection("user_info").where({
              id:that.data.visitor_id
          }).get().then(res=>{
             that.setData({
                 name:res.data[0].name
             })
             console.log("name:",that.data.name)
             db.collection("Visitor").add({
                 data:{
                     name:that.data.name,
                     time:myTime
                 }
            
             })
             wx.showToast({
                title: '识别为：'+that.data.name,
                icon: 'success',
              })
          });
      
      } catch (e) {
  console.log("error",e)
      }
      
  },
 
  

});